#include "flash_act.h"


#define USER_ADDRESS   				0X4600 //sector35--512byte --store the user define ambient light brightness value
#define SHELL_COLOR_ADDRESS		0X4200 //sector34--512byte --store the color of shell. 0x01/default:white   0x02:black



static en_result_t flash_write_halfword(uint32_t addr,uint16_t val);
static en_result_t flash_read_halfword(uint32_t addr, uint16_t *val);

static uint8_t arry[3]; //data_h,data_l,checksum


en_result_t read_user_halfword(uint16_t *val)
{
   return  flash_read_halfword(USER_ADDRESS,val);

}

en_result_t write_user_halfword(uint16_t val)
{
	
	return flash_write_halfword(USER_ADDRESS,val);

}

en_result_t read_shell_color_halfword(uint16_t *val)
{
		return  flash_read_halfword(SHELL_COLOR_ADDRESS,val);
}

en_result_t write_shell_color_halfword(uint16_t val)
{
	
	return flash_write_halfword(SHELL_COLOR_ADDRESS,val);

}

static en_result_t flash_read_halfword(uint32_t addr, uint16_t *val)
{
		uint8 *p = (uint8_t*)addr;
    arry[0] = p[0];
    arry[1] = p[1];
    arry[2] = p[2];
    
    if(arry[2] == (uint8_t)(arry[0] + arry[1])){
        *val = ((uint16_t)arry[0] << 8) + arry[1];
        return Ok;
    }else{
        *val = 0;
        return Error;
    }

}

static en_result_t flash_write_halfword(uint32_t addr,uint16_t val)
{
		arry[0] = val >> 8;
    arry[1] = val;
    arry[2] = arry[0] + arry[1];
    
    
    if(Ok != FLASH_SectorErase(addr)){
        return Error;
    }
    
    if(Ok != FLASH_WriteByte(addr,arry,3)){
        return Error;
    }
    
    if(Ok != FLASH_DataVerify((uint8_t*)addr,arry,3)){
        return Error;
    }
    
    return Ok;
}

